// 使用方法
// 简写方式：v-debounce:click="onClick"
// 复杂场景写法方式：v-debounce="{
//   handler: onSearch,  事件方法
//   event: 'input',     事件类型
//   delay: 800,         防抖时间
//   immediate: true     是否立即执行
// }" 

const debounce = {
    mounted(el, binding) {
        const {
            handler,      // 回调函数
            event = 'input', // 默认事件类型
            delay = 500,  // 防抖时间
            immediate = false // 是否立即执行
        } = parseBinding(binding);

        if (typeof handler !== 'function') {
            throw new Error('必须是一个函数');
        }

        let timeout = null;

        const debouncedFn = (...args) => {
            if (immediate && !timeout) {
                handler(...args);
            }

            clearTimeout(timeout);
            timeout = setTimeout(() => {
                if (!immediate) {
                    handler(...args);
                }
                timeout = null;
            }, delay);
        };
        el._debounce = {
            event,
            handler: debouncedFn,
            originalHandler: handler
        };
        el.addEventListener(event, debouncedFn);
    },

    beforeUnmount(el) {
        if (el._debounce) {
            el.removeEventListener(el._debounce.event, el._debounce.handler);
            delete el._debounce;
        }
    }
};
function parseBinding(binding) {
    if (typeof binding.value === 'function') {
        return {
            handler: binding.value,
            event: binding.arg || 'input',
            delay: parseInt(binding.modifiers.delay) || 500,
            immediate: binding.modifiers.immediate
        };
    }
    return {
        handler: binding.value.handler,
        event: binding.value.event || 'input',
        delay: binding.value.delay || 500,
        immediate: binding.value.immediate || false
    };
}
export default debounce